package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.*;

/**
 * <p>
 * 审核老师设置对应的详情 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-07-01
 */
@RestController
@RequestMapping("/api/trainAuditTeacherDetail")
public class TrainAuditTeacherDetailController {

    @Autowired
    ITrainAuditTeacherDetailService iTrainAuditTeacherDetailService;
    @Autowired
    ICourseTypeService iCourseTypeService;
    @Autowired
    ISkillItemsSetService iSkillItemsSetService;

    @Autowired
    private IEduVersionService iEduVersionService;

    @GetMapping("/findAll")
    public Result findAll(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                          @RequestParam(value = "schoolId", required = false) String schoolId,
                          @RequestParam(value = "auditTeacherSetId", defaultValue = "0", required = false) String auditTeacherSetId,
                          @RequestParam(value = "teacherName", required = false) String teacherName,
                          @RequestParam(value = "subType", required = false) Integer subType, // 教学审核时（type为1时）1：练课、2：备课、4：习题、5：发音
                          @RequestParam(value = "versionIdStr", required = false) String versionIdStr // 版本id
    ) {
        List<String> versionIdList = StringUtils.isNotBlank(versionIdStr) ? Arrays.asList(versionIdStr.split(",")) : new ArrayList<>();
        IPage<TrainAuditTeacherDetail> iPage = new Page<>(pageNum, pageSize);
        iTrainAuditTeacherDetailService.findAll(iPage, schoolId, auditTeacherSetId, teacherName, versionIdList);
        for (TrainAuditTeacherDetail trainAuditTeacherDetail : iPage.getRecords()){

            String classTypeIdStr = trainAuditTeacherDetail.getClassTypeIdStr();

            String itemsIdStr = trainAuditTeacherDetail.getItemsIdStr();

            String subjectsIdStr = trainAuditTeacherDetail.getSubjectsIdStr();

            String verIdStr = trainAuditTeacherDetail.getVersionIdStr();
            //获取科目名，多条数据用逗号隔开
            if (subjectsIdStr != null && !subjectsIdStr.isEmpty()) {
                String[] idss = subjectsIdStr.split(",");
                StringJoiner subjectsIdStrName = new StringJoiner(",");
                for (String id : idss) {
                    if (id != null && !id.isEmpty()) {
                        try {
                            subjectsIdStrName.add(CommonUtil.getSubjectsNameForId(Integer.valueOf(id)));
                        } catch (NumberFormatException e) {
                            // 处理无效的数字格式
                            subjectsIdStrName.add("未知科目");
                        }
                    }
                }
                trainAuditTeacherDetail.setSubjectsIdStrName(subjectsIdStrName.toString());
            }

            if (classTypeIdStr != null && !classTypeIdStr.isEmpty()) {
                String[] ids = classTypeIdStr.split(",");
                List<CourseType> courseTypeList = iCourseTypeService.list(new QueryWrapper<CourseType>()
                        .in("id", Arrays.asList(ids)));

                //获取班型名，多条数据用逗号隔开
                if (!courseTypeList.isEmpty()) {
                    if (courseTypeList.size() == 1) {
                        trainAuditTeacherDetail.setClassTypeName(courseTypeList.get(0).getName());
                    } else {
                        StringJoiner classTypeName = new StringJoiner(",");
                        for (CourseType courseType : courseTypeList) {
                            classTypeName.add(courseType.getName());
                        }
                        trainAuditTeacherDetail.setClassTypeName(classTypeName.toString());
                    }
                }
            }
            if (itemsIdStr != null && !itemsIdStr.isEmpty()) {
                String[] ids = itemsIdStr.split(",");
                List<SkillItemsSet> skillItemsSetList = iSkillItemsSetService.list(new QueryWrapper<SkillItemsSet>()
                        .in("id", Arrays.asList(ids)));

                //获取项目名，多条数据用逗号隔开
                if (!skillItemsSetList.isEmpty()) {
                    if (skillItemsSetList.size() == 1) {
                        trainAuditTeacherDetail.setItemsName(skillItemsSetList.get(0).getName());
                    } else {
                        StringJoiner itemsName = new StringJoiner(",");
                        for (SkillItemsSet skillItemsSet : skillItemsSetList) {
                            itemsName.add(skillItemsSet.getName());
                        }
                        trainAuditTeacherDetail.setItemsName(itemsName.toString());
                    }
                }
            }

            if (StringUtils.isNotBlank(verIdStr)) {
                String[] versionIds = verIdStr.split(",");
                List<EduVersion> list = iEduVersionService.listByIds(Arrays.asList(versionIds));
                StringJoiner versionNames = new StringJoiner(",");
                for (EduVersion eduVersion : list) {
                    versionNames.add(eduVersion.getName());
                }
                trainAuditTeacherDetail.setVersionNameStr(versionNames.toString());
            }

        }
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    @PostMapping("/save")
    public Result save(@RequestBody TrainAuditTeacherDetail trainAuditTeacherDetail) {

        QueryWrapper<TrainAuditTeacherDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("audit_teacher_set_id",trainAuditTeacherDetail.getAuditTeacherSetId());
        queryWrapper.eq("teacher_id",trainAuditTeacherDetail.getTeacherId());
        queryWrapper.eq(trainAuditTeacherDetail.getStationsId()!=null,"stations_id",trainAuditTeacherDetail.getStationsId());
        long count = iTrainAuditTeacherDetailService.count(queryWrapper);
        if (count > 0) {
            return new Result(Code.SAVE_ERROR, null, "该老师已存在");
        }

        boolean save = iTrainAuditTeacherDetailService.save(trainAuditTeacherDetail);
        if (save) {
            return new Result(Code.OK, null, Code.SAVE_OK_MSG);
        }
        return new Result(Code.ERROR, null, Code.SAVE_ERROR_MSG);
    }

    @PutMapping("/update")
    public Result update(@RequestBody TrainAuditTeacherDetail trainAuditTeacherDetail){
        QueryWrapper<TrainAuditTeacherDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("id",trainAuditTeacherDetail.getId());
        queryWrapper.eq("audit_teacher_set_id",trainAuditTeacherDetail.getAuditTeacherSetId());
        queryWrapper.eq("teacher_id",trainAuditTeacherDetail.getTeacherId());
        queryWrapper.eq(trainAuditTeacherDetail.getStationsId()!=null,"stations_id",trainAuditTeacherDetail.getStationsId());
        long count = iTrainAuditTeacherDetailService.count( queryWrapper);
        if (count > 0) {
            return new Result(Code.UPDATE_ERROR, null, "该老师已存在");
        }
        // 由于无法将值改为空，所以这里先删除，再重新添加
        boolean del = iTrainAuditTeacherDetailService.removeById(trainAuditTeacherDetail.getId());

        boolean save = iTrainAuditTeacherDetailService.save(trainAuditTeacherDetail);

//        boolean update = iTrainAuditTeacherDetailService.updateById(trainAuditTeacherDetail);
//        if (update){
//            return new Result(Code.OK, null, Code.UPDATE_OK_MSG);
//        }
//        return new Result(Code.ERROR, null, Code.UPDATE_ERROR_MSG);
        return new Result(Code.OK, null, Code.UPDATE_OK_MSG);
    }

    @DeleteMapping("/batchDelete")
    public Result batchDelete(@RequestBody Map reMap) {
        List<String> ids = (List<String>) reMap.get("ids");
        if (ids == null || ids.isEmpty()){
            return new Result(Code.DELETE_ERROR, "", "请选择要删除的id");
        }
        QueryWrapper<TrainAuditTeacherDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        boolean remove = iTrainAuditTeacherDetailService.remove(queryWrapper);
        if (remove) {
            return new Result(Code.OK, null, Code.DELETE_OK_MSG);
        }
        return new Result(Code.ERROR, null, Code.DELETE_ERROR_MSG);
    }

}
